package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.Order;
import csu.web.mypetstore.service.AccountService;
import csu.web.mypetstore.service.LogService;
import csu.web.mypetstore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class NewOrderServlet extends HttpServlet {
    private static final String NEWORDER_FORM = "/WEB-INF/jsp/order/newOrder.jsp";
    private static final String COMFIRM_FORM = "/WEB-INF/jsp/order/ComFirmOrder.jsp";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session =req.getSession();
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        Cart cart =(Cart) session.getAttribute("cart");

        String username = loginAccount.getUsername();

        String cardType = req.getParameter("cardType");
        String number = req.getParameter("Number");
        String Odate = req.getParameter("ODate");
        String firstName = req.getParameter("FirstName");
        String lastName = req.getParameter("LastName");
        String address1 = req.getParameter("Address1");
        String address2 = req.getParameter("Address2");
        String city = req.getParameter("City");
        String state = req.getParameter("State");
        String zip = req.getParameter("Zip");
        String country = req.getParameter("Country");
        String Edate = req.getParameter("EDate");

        Order order = new Order();
        order.setExprdate(Edate);
        order.setUsername(username);
        order.setType(cardType);
        order.setPhone(number);
        order.setDate(Odate);
        order.setFirstName(firstName);
        order.setLastname(lastName);
        order.setAddress1(address1);
        order.setAddress2(address2);
        order.setCity(city);
        order.setState(state);
        order.setZip(zip);
        order.setCountry(country);

        double Value = cart.getSubTotal().doubleValue();
        order.setPrice(Value);


        System.out.println(order.getFirstName());
        OrderService orderService = new OrderService();
        orderService.addOrder(order);

        session.setAttribute("order", order);
        req.setAttribute("order", order);
        if(loginAccount==null){
            resp.sendRedirect("signonForm");
        }
        else {
            req.getRequestDispatcher(COMFIRM_FORM).forward(req,resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
